package org.jef.socket.websocket;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jef.socket.event.EventType;
import org.jef.socket.msg.IMsg;
import org.jef.socket.thread.CountDownMsg;
import org.jef.socket.thread.JefCountDownUtils;
import org.jef.socket.thread.SingletonThreadPool;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * 消息监听对象，接收订阅消息
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JefRedisReceiver implements MessageListener {

    public static final String UTF8 = "UTF-8";

    private final IWebSocket webSocket;

    private final RedisTemplate jefRedisTemplate;

    /**
     * 处理接收到的订阅消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());// 订阅的频道名称
        String msg = "";
        try {
            msg = new String(message.getBody(), StandardCharsets.UTF_8);//注意与发布消息编码一致，否则会乱码
            if (!StringUtils.isEmpty(msg)){
                if (EventType.TOPIC_WEBSOCKET.getValue().equals(channel)) {
                    IMsg imsg = (IMsg) jefRedisTemplate.getValueSerializer().deserialize(message.getBody());
                    Long userId = imsg.getUserId();
                    String roomId = imsg.getRoomId();
                    if (userId != null && userId != 0 && roomId != null && !"".equals(roomId)) {
                        // userId不为0说明是点对点消息
                        webSocket.sendToUser(roomId, userId, imsg);
                    } else if (roomId != null && !"".equals(roomId) && (userId == null || userId == 0)) {
                        // 房间内广播
                        webSocket.roomBroadcast(imsg, roomId);
                    } else {
                        // 广播消息
                        webSocket.broadcast(imsg);
                    }
                } else if (EventType.TOPIC_COUNTDOWN.getValue().equals(channel)) {

                    CountDownMsg countDownMsg = JSON.parseObject(msg, CountDownMsg.class);
                    if (countDownMsg.getType().equals(JefCountDownUtils.PAUSE_STATE)) {
                        // 如果是暂停，需要调用暂停线程
                        SingletonThreadPool.shutdown(countDownMsg.getMsg(), false);
                    }

                    if (countDownMsg.getType().equals(JefCountDownUtils.RESET_STATE)) {
                        // 如果是重置状态，需要调用暂停线程
                        SingletonThreadPool.shutdown(countDownMsg.getMsg(), true);
                    }
                }
            }else{
                log.debug("消息内容为空，不处理。");
            }
        } catch (Exception e) {
            log.error("处理消息异常：", e);
        }
    }
}

